#include <QApplication>
#include <QTextCodec>
#include <QStringList>
#include <util/gref.h>

#include "components.h"
#include "scripting.h"

#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
  if (argc < 2)
  {
    std::cout << "Useage: framework.exe <entry script>" << std::endl;
    return -1;
  }

  QApplication app(argc, argv);
  QApplication::setStyle("plastique");

  ::setlocale(LC_CTYPE, "Russian");
  QTextCodec::setCodecForCStrings(QTextCodec::codecForName("Windows-1251"));
  QTextCodec::setCodecForLocale(QTextCodec::codecForName("Windows-1251"));

  GRefScope< ComponentsScope > componentsScope;
  GRefScope< ScriptingScope  > scriptingScope;

  QScriptEngine &engine = GRef< ScriptingScope >()->mEngine;

  { // fill command line arguments
    QScriptValue argArray = engine.newArray(argc);

    for (int i = 0; i < argc; ++i)
      argArray.setProperty(i, argv[i]);

    engine.globalObject().setProperty("Arg", argArray);
  }

  RunFile(argv[1]);

  { // check exit code at start
    QScriptValue exitCodeValue = engine.globalObject().property("ExitCode");

    if (!exitCodeValue.isUndefined())
      return exitCodeValue.toInteger();
  }

  const int result = app.exec();

  return result;
}